<script setup>
import { ref, onMounted,reactive} from 'vue'
import {ElMessage,ElMessageBox} from "element-plus";
import {queryAllArticle, addArticle, updateArticle, deleteArticle} from "@/api/article";
import axios from "axios";

const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true);
const total = ref(0);
const tableData = ref([])
const userId = ref('')
const username = ref('')
const formInline =ref({
  title: '',
  consultant_id: null
});
// 对话框控制
const dialogVisible = ref(false)
const mode = ref('add') // add/edit/view
const formData = ref({
  id: null,
  title: '',
  summary: '',
  consultant_id: null,
  cover_image: '',
  views: '',
  favorites: '',
  create_time: '',
  name:''
})
// 添加选中的行数据
const selectedRows = ref([]);
const uploadRef = ref(null);
const levelOptions = ref([]);
const searchFM = async () => {
  let response;
  try {
    response = await axios({
      url: 'api/consultant/search',
      method: 'get',
      params: {
        pageNum:1,
        pageSize:10
      }
    })
    console.log('分类数据:', response)
    if (response.data.code) {
      levelOptions.value = response.data.data.rows.map(item => ({
        id: item.id,
        name: item.name
      }))
    }
  } catch (e) {
    ElMessage.error(response.data.msg || '请求失败')
  }
}




const handleSuccess = (response) => {
  if (response.code === 1) {
    formData.value.cover_image = 'http://localhost:8080' + response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请重试')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleImageError = (e) => {
  e.target.style.display = 'none'
}
// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
})

onMounted(() => {
  // 从 localStorage 读取数据
  const userInfoStr = localStorage.getItem('userInfo')

  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      userId.value = userInfo.id || ''
      username.value = userInfo.username || '' // 确保非 null
    } catch (error) {
      console.error('解析用户数据失败:', error)
    }
  }
  search();
  searchFM();

})
const search=async ()=>{
  const restult = await queryAllArticle(currentPage.value,pageSize.value,formInline.value.title,userId.value)
  console.log("=============",restult)
  if(restult.code){
    tableData.value = restult.data.rows;
    total.value = restult.data.total
  }else{
    ElMessage.error(restult.msg)
  }
}
// 通用提交处理
const handleSubmit = () => {
  if (mode.value === 'add') {
    handleAddSubmit()
  } else if (mode.value === 'edit') {
    handleEditSubmit()
  }
}
// 提交添加
const handleAddSubmit = async () => {
  try {
    const payload = {
      ...formData.value,
      consultant_id: Number(formData.value.consultant_id),
    }
    const result = await addArticle(payload);
    if (result.code === 1) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '添加失败');
    }
  } catch (error) {
    ElMessage.error('添加请求失败');
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const payload = {
      ...formData.value,
      consultant_id:  Number(formData.value.consultant_id),
    }
    const result = await updateArticle(payload);
    if (result.code === 1) {
      ElMessage.success('更新成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新请求失败')
  }
}

// 打开添加对话框
const openAddDialog = () => {
  mode.value = 'add'
  formData.value = {
    id: null,
    title: '',
    summary: '',
    consultant_id: null,
    cover_image: '',
    views: 0,
    favorites: 0,
    create_time: ''
  }
  if (levelOptions.value.length ===0){
    searchFM().then(() => {
      dialogVisible.value = true
    })
  }else {
    dialogVisible.value = true
  }
}

// 打开编辑对话框
const openEditDialog = (row) => {
  mode.value = 'edit'
  formData.value = { ...row, create_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
    consultant_id:row.consultant_id
  }
  // 强制刷新分类数据
  searchFM().finally(() => {
    dialogVisible.value = true
  })
}

// 打开详情对话框
const openViewDialog = (row) => {
  mode.value = 'view'
  formData.value = { ...row,consultant_id:row.consultant_id}
  dialogVisible.value = true
}

// 模式映射配置
const modeMap = reactive({
  add: { title: '添加文章', submit: handleAddSubmit },
  edit: { title: '编辑文章', submit: handleEditSubmit },
  view: { title: '文章详情' }
})


const handleDelete = async (idOrRows) => {
  // 统一处理为数组
  let ids = []
  // 数据类型转换逻辑
  if (typeof idOrRows === 'number') {
    ids = [idOrRows]
  } else if (Array.isArray(idOrRows)) {
    ids = idOrRows.map(item => Number(item.id))
  } else {
    ids = selectedRows.value.map(item => Number(item.id))
  }

  try {
    await ElMessageBox.confirm('确定删除选中数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await deleteArticle(ids)
    if (result.code === 1) {
      ElMessage.success('删除成功')
      // 清空选中项
      selectedRows.value = []
      search()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    console.log('取消删除')
  }
}

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}
</script>

<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="文章名称">
      <el-input v-model="formInline.title" placeholder="请输入文章名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="openAddDialog">+添加文章</el-button>
      <el-button type="danger" @click="handleDelete">-批量删除</el-button>
    </el-form-item>
  </el-form>


  <el-table :data="tableData" border style="width: 100%"  @selection-change="val => selectedRows = val">
    <el-table-column type="selection"/>
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="title" label="文章名称"/>
    <el-table-column prop="summary" label="文章简介"/>
    <el-table-column prop="consultant_id" label="文章作者">
      <template #default="scope">
        {{ scope.row.consultant.name }}
      </template>
    </el-table-column>
    <el-table-column prop="cover_image" label="文章图片">
      <template #default="scope">
        <div class="image-container">
          <img
              v-if="scope.row.cover_image"
              :src="scope.row.cover_image"
              @error="handleImageError"
              :alt="scope.row.title"
          >
          <div v-else class="image-placeholder">
            <el-icon><Picture /></el-icon>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="views" label="阅读数量"/>
    <el-table-column prop="favorites" label="收藏数量"/>
    <el-table-column prop="create_time" label="创建时间"/>
    <el-table-column label="操作" width="280px">
      <template #default="scope">
        <el-button type="warning" size="mini"  @click="openViewDialog(scope.row)">详情</el-button>
        <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  <!-- 通用对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="modeMap[mode].title"
      width="40%"
  >
    <el-form
        :model="formData"
        label-width="100px"
        :disabled="mode === 'view'"
    >
      <!-- 查看模式显示ID和创建时间 -->
      <template v-if="mode === 'view'">
        <el-form-item label="FM ID">
          <el-input v-model="formData.id" readonly />
        </el-form-item>
      </template>

      <!-- 公共字段 -->
      <el-form-item label="文章名" prop="title" :rules="formRules.title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="文章简介" prop="title">
        <el-input v-model="formData.summary" />
      </el-form-item>
      <el-form-item label="文章作者" prop="title">
        <el-input v-model="username" :readonly="true"/>
      </el-form-item>

      <el-form-item label="文章图片" prop="coverImage">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="/api/img/upload"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
        >
          <img v-if="formData.cover_image" :src="formData.cover_image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="阅读数量" prop="views">
        <el-input v-model="formData.views" :readonly="true"/>
      </el-form-item>
      <el-form-item label="收藏数量" prop="favorites">
        <el-input v-model="formData.favorites" :readonly="true"/>
      </el-form-item>


      <!-- 在对话框的表单中修改这部分 -->
      <el-form-item label="创建时间" v-if="mode === 'view'">
        <el-date-picker
            v-model="formData.create_time"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            readonly
            disabled
        />
      </el-form-item>

      <!-- 添加编辑时的时间字段（如果需要编辑时间） -->
      <el-form-item label="创建时间" v-else-if="mode === 'edit'">
        <el-date-picker
            v-model="formData.create_time"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="创建时间" v-else-if="mode === 'add'">
        <el-date-picker
            v-model="formData.create_time"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
          v-if="mode !== 'view'"
          type="primary"
          @click="handleSubmit">确认
      </el-button>
    </template>
  </el-dialog>




  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                 :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                 layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                 @current-change="handleCurrentChange" />

</template>
<style scoped>
/* 全局边距调整 */
.demo-form-inline {
  margin-bottom: 20px;
}

/* 表单元素间距调整 */
.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
  margin-right: 10px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 按钮组间距 */
.el-button + .el-button {
  margin-left: 12px;
}

/* 表格调整 */
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 分页组件调整 */
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 对话框表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 音频控件宽度适配 */
audio {
  width: 100%;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
/* 统一图片容器尺寸 */
.image-container {
  width: 100px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 修正真实图片样式 */
.el-table .cell img {
  width: 100%;
  height: 100%;
  object-fit: contain;  /* 保持比例填充 */
}

/* 调整占位符为绝对定位 */
.image-placeholder {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

/* 添加父级对齐容器 */
.el-table__cell > .cell {
  display: flex !important;
  justify-content: center;
  min-height: 62px; /* 包含边框高度 */
}

/* 统一悬停状态容器 */
.image-container:hover {
  transform: scale(1.8);
  z-index: 1000;
  transition: all 0.3s ease;
}

/* 统一上传按钮样式 */
.el-button :deep(.el-icon) {
  vertical-align: middle;
  margin-right: 5px;
}


/* 统一操作按钮间距 */
.el-table .el-button {
  margin: 4px;
}

</style>